package main.loading;

import main.InitGame;

public class LoadingThread extends Thread {
	
	private LoadingProcess loadingProcess;
	private boolean abort;
	
	public LoadingThread(LoadingProcess loadingProcess) {
		this.loadingProcess = loadingProcess;
	}
	
	public void abort() {
		if(loadingProcess.canBeAborted()) abort = true;
	}
	
	@Override
	public void run() {
		int i = 0;
		abort = false;
		
		InitGame.get().loadingStarted(loadingProcess.getLoadingState());
		
		while(loadingProcess.hasNext(i) && !abort) {
			try {
				LoadingStep step = loadingProcess.getNextStep(i);
				if(!step.perform()) return;
				
				loadingProcess.updateScreen(step.getLoadingStep());
			} catch(Exception e) {
				e.printStackTrace();
				return;
			} finally { i++; }
		}
		
		if(abort) loadingProcess.abort();
		else loadingProcess.finish();
		
		InitGame.get().loadingStopped(loadingProcess.getLoadingState());
		
		loadingProcess.cleanup();
		loadingProcess = null;
	}
}